# #---------------------------------------------
# # Place code that specific to your project in this file. helper_common is referencing this file.
# #---------------------------------------------
def start_selenium_with_url_of_report(report_name)
    start_selenium
    url = get_url_from_submission_log(report_name)
    open_URL(url)
end

# #---------------------------------------------

def submit_to_repo_with(basedir, report_name, expected_result, open_browser)
    begin
        log_write "----------------#{report_name}----------------"

        log_write "1.Open doc '#{basedir}#{report_name}'"
        autoit_run('winword.exe "' + basedir + report_name + '"')

        log_write "2.Wait for Word open"
        autoit_win_activate("#{report_name} - Microsoft Word", "")
        autoit_win_wait_active("#{report_name} - Microsoft Word", "", 30)

        log_write "3.Press ALT+h"
        autoit_send("!h")

        log_write "4.Press LEFT"
        autoit_send("{LEFT}")
        #~ autoit_send("{LEFT}")
        # #autoit_send("{RIGHT}")

        log_write "5.Press r"
        autoit_send("r")

        log_write "6.Wait for Document submission"
        autoit_win_activate("Document submission", "")
        autoit_win_wait_active("Document submission", "", 60)
        submission_status = autoit_get_window_text("Document submission")
        expected_status = "&Yes
&No
#{expected_result}
        "
        assert_is_text_equl(submission_status, expected_status)
        log_write "Submission Result: #{submission_status}"

        if (open_browser.eql?("Yes"))
            log_write "7.Press Yes"
            autoit_win_activate("Document submission", "")
            autoit_send("Y")
            url = get_url_of_submitted_doc(report_name)
        else
            log_write "7.Press No"
            autoit_win_activate("Document submission", "")
            autoit_send("{ENTER}")
            url = "Submit Without Open Browser"
        end

        log_write "----------------------------------------------------------------"
        log_write "8.Close Word window"
        autoit_kill_process("winword.exe")
        autoit_sleep(2000)
        return url

    rescue => err
        raise(err)
    end
end

# #---------------------------------------------

def create_base_url_of_submission(submission_file, url_of_submission)
    base_url = url_of_submission.sub(/\?.*/, "")
    create_summary_for_submitted_report(submission_file, "New_Publication_Page", base_url)
end

# #---------------------------------------------

def submit_report(element_SubmitReport)
    begin
        base_dir = element_SubmitReport.attributes["basedir"]
        report_name = element_SubmitReport.attributes["report_name"]
        open_browser = element_SubmitReport.attributes["open_browser"]
        expected_message_unprocessed = element_SubmitReport.attributes["expected_message"]
        expected_message = process_value_to_see_if_property_is_used(expected_message_unprocessed)

        url_of_submission = submit_to_repo_with(base_dir, report_name, expected_message, open_browser)
        create_summary_for_submitted_report("Submission_log.xml", report_name, url_of_submission)
        if !url_of_submission.eql?("Submit Without Open Browser")
            create_base_url_of_submission("Submission_log.xml", url_of_submission)
        end
    rescue => err
        $error_from_submission = 1
        raise err
    end
end

# #---------------------------------------------

def submit_doc(test_case_file, case_id)
    xml_doc = Document.new(File.new(test_case_file))
    doc_file = XPath.first(xml_doc, "//scenario[@No=#{case_id}]/report").get_text.to_s
    doc_basedir = XPath.first(xml_doc, "//scenario[@No=#{case_id}]/report").attributes["basedir"].to_s
    puts doc_file, doc_basedir
    submit_to_repo_with(doc_basedir, doc_file)
end

# #---------------------------------------------

def submit_doc_in_path(path)
    docs = Dir.entries(path)
    puts docs.length
    counter = 0
    docs.each do |doc|
        if doc =~ /.doc/
            log_write "##{counter}"
            submit_to_repo_with(doc)
            counter += 1
        end
    end
end

# #---------------------------------------------

def get_url_of_submitted_doc(doc)
    autoit_win_activate("New Publication", "")
    autoit_win_wait_active("New Publication", "", 30)
    url = autoit_control_get_text("New Publication", "", "Edit1")
    log_write "INFO: get url (#{url}) for '#{doc}'"
    autoit_close("New Publication")
    return url
end

# #---------------------------------------------

def create_summary_for_submitted_report(file_name, report_name, url)
    t = Time.now
    if File.exist?(file_name)
        doc = Document.new(File.new(file_name))
        xml_file = File.new(file_name, "w+")
    else
        xml_file = File.new(file_name, "w+")
        doc = Document.new '<?xml version="1.0" encoding="UTF-8"?><root/>'
    end
    root_node = doc.root
    element_report = XPath.first(root_node, "//Report[@name='#{report_name}']")
    if (element_report)
        element_submission = get_xml_element_s_parent(element_report)
        element_submission.elements[2].attributes["value"] = url
        element_submission.elements[3].attributes["value"] = t.to_s
        element_submission.attributes["times"] = (element_submission.attributes["times"].to_i + 1).to_s
    else
        element_id = root_node.get_elements("*").length + 1
        element_for_submission = root_node.add_element("Submission", {"id" => element_id, "times" => "1" })
        element_for_submission.add_element "Report", {"name" => report_name}
        element_for_submission.add_element "URL", {"value" => url}
        element_for_submission.add_element "Time", {"value" => t.to_s}
    end
    doc.write(Output.new( xml_file, "ISO-8859-1"), 8, false, true)
    xml_file.close
end

# #---------------------------------------------

def wait_for_flash_message_to_appear
    begin
        selenium_wait_for_condition("if(selenium.browserbot.getCurrentWindow().document.getElementById('flashMessage') == null)
                                  {
                                      false;
                                  } 
                                  else 
                                      {
                                          if(selenium.browserbot.getCurrentWindow().document.getElementById('flashMessage').innerText != '')
                                          {
                                              true;
                                          } 
                                          else 
                                          {
                                              false;
                                          }
                                    }", 60000)
        return selenium_get_text("//span[@id='flashMessage']")
    rescue => err
        raise "ERROR: Wait for flash message to appear got #{err}"
    end
end

# #---------------------------------------------

def wait_for_flash_message_to_disappear
    begin
        selenium_wait_for_condition("if(selenium.browserbot.getCurrentWindow().document.getElementById('flashMessage') != null)
                                  {
                                      if(selenium.browserbot.getCurrentWindow().document.getElementById('flashMessage').innerText == '')
                                          {
                                              true;
                                          } 
                                          else 
                                          {
                                              false;
                                          }
                                  }
                                  else
                                  {
                                      false;
                                  } ", 60000)
    rescue => err
        raise "ERROR: Wait for flash message to disappear got #{err}"
    end
end

# #---------------------------------------------

def wait_for_flash_message(expected_flash_message)
    begin
        actual_flash_message = wait_for_flash_message_to_appear
        assert_is_text_equl(actual_flash_message, expected_flash_message)
        wait_for_flash_message_to_disappear
    rescue => err
        raise "ERROR: Flash Message is unexpected: #{err}"
    end
end

# #---------------------------------------------

def wait_for_save_as_draft(expected_flash_messae)
    begin
        actual_flash_message = wait_for_flash_message_to_appear
        assert_is_text_equl(actual_flash_message, expected_flash_messae)
        wait_for_flash_message_to_disappear
    rescue => err
        raise "ERROR: Saving result is unexpected: #{err}"
    end
end

# #---------------------------------------------

def wait_for_distribute(expected_flash_messae)
    begin
        actual_flash_message = wait_for_flash_message_to_appear
        assert_is_text_equl(actual_flash_message, expected_flash_messae)
        wait_for_flash_message_to_disappear
    rescue => err
        raise "ERROR: Result of distributing is unexpected: #{err}"
    end
end

# #---------------------------------------------

def wait_for_printing_spec
    selenium_wait_for_condition("if(selenium.browserbot.getCurrentWindow().document.getElementById('printingSpec').style.display != 'none')
                                  {
                                      true;
                                  }", 5000)
end

# #---------------------------------------------

def wait_for_related_pub_search_form
    selenium_wait_for_condition("if(selenium.browserbot.getCurrentWindow().document.getElementById('relationForm').style.display != 'none')
                                  {
                                      true;
                                  }", 5000)
end

# #---------------------------------------------

def wait_for_publication_log
    selenium_wait_for_condition("if(selenium.browserbot.getCurrentWindow().document.getElementById('pubLog').style.display != 'none')
                                  {
                                      true;
                                  }", 5000)
end

# #---------------------------------------------

def wait_for_related_pub_search_result
    wait_for_child("searchResult")
end

# #---------------------------------------------

def wait_for_FMI_search_result
    wait_for_child("stocksSearchResult")
end

# #---------------------------------------------

def wait_for_FMI_selected_stock
    wait_for_child("stocksSelected")
end

# #---------------------------------------------

def wait_for_CT_search_result
    wait_for_child("researchResultsUL")
end

# #---------------------------------------------

def wait_for_populate_default
    wait_for_child("1")
end

# #---------------------------------------------

def wait_for_populate_recent
    wait_for_child("10")
end

# #---------------------------------------------

def get_url_from_submission_log(report_name)
    submission_log = Document.new(File.new("submission_log.xml", "r"))
    element_report = XPath.first(submission_log, "//Report[@name='#{report_name}']")
    if (element_report != nil) then
        element_url = element_report.next_element
        element_url.attributes["value"]
    else
        raise "ERROR: Report [#{report_name}] is not found."
    end
end

# #---------------------------------------------s

def get_attribute_name_of_element(element)
    element.attributes["name"]
end

# #---------------------------------------------

def get_attribute_value_of_element(element)
    element.attributes["value"]
end

# #---------------------------------------------

def get_index_of_sepecific_publication(draft_id, draft_name)
    draft_amount = selenium_get_xpath_count(draft_id.sub(/\[HHH\].*/, ""))
    index = -1
    1.upto(draft_amount.to_i) do |i|
        if (index != -1) then
            return index
        end
        draft = draft_id.sub(/HHH/, "#{i}")
        begin
            current_draft_text = selenium_get_text(draft)
            puts current_draft_text
        rescue => err
            log_write "WARNIGN: #{err}"
        end
        if (current_draft_text.eql?(draft_name))
            index = i
        end
    end
    if (index != -1)
        index
    else
        raise "ERROR: Specified publication is not found on the page."
    end
end

# #---------------------------------------------

def get_stock_control_id(stock_control_name, stock_number)
    ValueProcessor.const_get(stock_control_name).sub(/HHH/, stock_number.to_s)
end

# #---------------------------------------------

def is_stock_present(stock_name)
    found = -1
    stock_amount = selenium_get_xpath_count("//table[@id='#{get_control_id("STK")}']/tbody/tr").to_i
    1.upto(stock_amount) do |i|
        actual_stock_name = selenium_get_value(get_stock_control_id("TBX_STOCK", i-1))
        if (actual_stock_name == stock_name)
            found = i-1
        end
    end
    found
end

# #---------------------------------------------

def set_value_for_stock(tbody_id, element_STK)
    stock_amount = selenium_get_xpath_count("//table[@id='#{tbody_id}']/tbody/tr").to_i

    case element_STK.attributes["type"]
    when /Add/
        if (stock_amount == 1 && is_stock_present("") == 0) then
            perform_action_on_stock(0, element_STK)
        else
            selenium_click(get_control_id("LNK_ADDROW"))
            perform_action_on_stock(stock_amount, element_STK)
        end
    when /Remove/
        stock_id = element_STK.attributes["stock_id"]
        index = is_stock_present(stock_id)
        if (index != -1) then
            selenium_click(get_stock_control_id("LNK_REMOVE", index+1))
        else
            raise "ERROR: There is no stock named [#{stock_id}]. Remove failed."
        end
    else
        raise "ERROR: This element is neither Add nor Remove."
    end
end

# #---------------------------------------------

def perform_action_on_stock(stock_number, element_STK)
    stock_id = element_STK.attributes["stock_id"]
    if (stock_id != nil)
        stock_control_id = get_stock_control_id("TBX_STOCK", stock_number)
        set_value_to_textbox(stock_control_id, stock_id)
    end

    recommendation = element_STK.attributes["recommendation"]
    if (recommendation != nil)
        stock_control_id = get_stock_control_id("DRP_RECOMMENDATION", stock_number)
        set_value_to_dropdown(stock_control_id, recommendation)
    end

    recommendation_change = element_STK.attributes["recommendation_change"]
    if (recommendation_change != nil)
        stock_control_id = get_stock_control_id("DRP_RECOMM_CHANGE", stock_number)
        set_value_to_dropdown(stock_control_id, recommendation_change)
    end

    earning_revision = element_STK.attributes["earning_revision"]
    if (earning_revision != nil)
        stock_control_id = get_stock_control_id("DRP_EARNING_REVISION", stock_number)
        set_value_to_dropdown(stock_control_id, earning_revision)
    end

    initiating_coverage = element_STK.attributes["initiating_coverage"]
    if (initiating_coverage != nil)
        stock_control_id = get_stock_control_id("CHK_INITIATING_COVERAGE", stock_number)
        set_value_to_checkbox(stock_control_id, initiating_coverage)
    end

    primary = element_STK.attributes["primary"]
    if (primary != nil)
        stock_control_id = get_stock_control_id("CHK_PRIMARY", stock_number)
        set_value_to_checkbox(stock_control_id, primary)
    end
end

# #---------------------------------------------

def preview_email(element_preview_email)
    control_name = get_attribute_name_of_element(element_preview_email)
    control_id = get_control_id(control_name)
    selenium_click(control_id)

    selenium_open_window("", "PreviewEmail_#{selenium_get_value("_windowId")}")
    selenium_wait_for_pop_up("PreviewEmail_#{selenium_get_value("_windowId")}", 30000)

    preview_title = selenium_get_all_window_title(1)

    t = Time.now
    path_to_save = element_preview_email.attributes["path_to_save"]
    path_to_save = process_value_to_see_if_property_is_used(path_to_save)

    selenium_capture_screenshot("#{path_to_save}/#{preview_title}-#{t.mon}#{t.day}_#{t.hour}#{t.min}.png")
end

# #---------------------------------------------

def click_publication(publication_id, publication_name)
    publication_index = get_index_of_sepecific_publication(publication_id, publication_name)
    pub = publication_id.sub(/HHH/, "#{publication_index}")
    selenium_click(pub)
end

# #---------------------------------------------

def click_publication_log(publication_id, publication_name)
    publication_index = get_index_of_sepecific_publication("//tbody[@id='distributed:distPublications:tbody_element']/tr[HHH]/td[2]/a", publication_name)
    pub = publication_id.sub(/HHH/, "#{publication_index}")
    selenium_click(pub)
end

# #---------------------------------------------

def select_draft(draft_id, draft_name, control_name)
    if (control_name.eql?"SPN_SELECT_DRAFT")
        draft_link_id = draft_id.sub('/td[1]/input', '/td[3]/a')
    end
    if (control_name.eql?"SPN_SELECT_PENDING_DISTRIBUTION")
        draft_link_id = draft_id.sub('/td[1]/input[2]', '/td[2]')
    end
    draft_index = get_index_of_sepecific_publication(draft_link_id, draft_name)
    draft = draft_id.sub(/HHH/, "#{draft_index}")
    set_value_to_checkbox(draft, "on")
end

# #========================================================================================

def handler_for_action_STK(element_STK)
    control_name = get_attribute_name_of_element(element_STK)
    control_id = get_control_id(control_name)
    set_value_for_stock(control_id, element_STK)
end

# #---------------------------------------------

def handler_for_action_SPN(element_SPN)
    control_name = get_attribute_name_of_element(element_SPN)
    control_id = get_control_id(control_name)
    value_unprocessed = get_attribute_value_of_element(element_SPN)
    value = process_value_to_see_if_property_is_used(value_unprocessed)
    case control_name
    when /PUBLICATION_LOG/
        click_publication_log(control_id, value)
    when /CLICK/
        click_publication(control_id, value)
    when /SELECT/
        select_draft(control_id, value, control_name)
    else
        raise "ERROR: #{control_name} is not recognized."
    end
end

# #---------------------------------------------

def handler_for_action_INP_4ENP(element_INP)
    control_name = get_attribute_name_of_element(element_INP)
    control_id = get_control_id(control_name)

    path_unproccessed = element_INP.attributes["path"]
    path = process_value_to_see_if_property_is_used(path_unproccessed)

    filename_unprocessed = get_attribute_value_of_element(element_INP)
    filename = process_value_to_see_if_property_is_used(filename_unprocessed)

    t = Time.now
    time_now = "#{t.mon}#{t.day}_#{t.hour}#{t.min}_#{t.sec}"

    new_filename = filename.sub(".pdf", "_" + time_now + ".pdf")
    if (!new_filename.eql?(filename))
        FileUtils.cp(path + filename, path + new_filename)
        filename = new_filename
        $pdf_filename = filename
    end

    set_value_for_input(control_id, path + filename)
end

# #---------------------------------------------

def handler_for_action_BTN_4ENP(element_BTN)
    control_name = get_attribute_name_of_element(element_BTN)
    case control_name
    when /PREVIEW_EMAIL/
        preview_email(element_BTN)
    when /PDF_OPTION/
        set_pdf_option(element_BTN)
    else
        control_id = get_control_id(control_name)
        wait_for_button_to_be_enable(control_id)
        selenium_click(control_id)
    end
end

# #---------------------------------------------

def set_pdf_option(element)
    control_name = get_attribute_name_of_element(element)
    control_id = get_control_id(control_name)

    category_id = element.attributes["category"]
    publication_id = element.attributes["publication"]
    pdf_option_id = element.attributes["pdf_option"]

    control_id = control_id.sub(/CAT_ID/, "#{category_id}")
    control_id = control_id.sub(/PUB_ID/, "#{publication_id}")
    control_id = control_id.sub(/PDF_ID/, "#{pdf_option_id}")

    selenium_click(control_id)
end

# #---------------------------------------------

def set_publication_date(date_string)
    t = Time.now
    case date_string
    when /New_Publication/
        run_script("var date = new Date('#{t.day } #{Time.const_get('RFC2822_MONTH_NAME')[t.month-1]} #{t.year}'); self.thisPage.pubForm.basicInfoSection.pubDatePicker.setDate(date);")
    when /New_Consolidation/
        run_script("var date = new Date('#{t.day } #{Time.const_get('RFC2822_MONTH_NAME')[t.month-1]} #{t.year}'); self.thisPage.consolidationForm.publicationDatePicker.setDate(date);")
    else
    end
end

# #========================================================================================

def assert_is_stock_present(element_STK)
    found_match = false
    stock_amount = selenium_get_xpath_count("//tbody[@id='publicationInfo:coveredStocks:tbody_element']/tr")
    expected_stock_name = element_STK.attributes["stock_id"]
    0.upto(stock_amount.to_i - 1) do |i|
        begin
            actual_stock_name = selenium_get_value(get_stock_control_id("TBX_STOCK", i))
            if (actual_stock_name == expected_stock_name)
                expected_recommendation = element_STK.attributes["recommendation"]
                if (expected_recommendation != nil)
                    control_id_recommendation = get_stock_control_id("DRP_RECOMMENDATION", i)
                    assert_is_option_selected(control_id_recommendation, expected_recommendation)
                end

                expected_recommendation_change = element_STK.attributes["recommendation_change"]
                if (expected_recommendation_change != nil)
                    control_id_recomm_change = get_stock_control_id("DRP_RECOMM_CHANGE", i)
                    assert_is_option_selected(control_id_recomm_change, expected_recommendation_change)
                end

                expected_earning_revision = element_STK.attributes["earning_revision"]
                if (expected_earning_revision != nil)
                    control_id_recomm_change = get_stock_control_id("DRP_EARNING_REVISION", i)
                    assert_is_option_selected(control_id_recomm_change, expected_earning_revision)
                end

                expected_initiating_coverage = element_STK.attributes["initiating_coverage"]
                if (expected_initiating_coverage != nil)
                    control_id_recomm_change = get_stock_control_id("CHK_INITIATING_COVERAGE", i)
                    assert_is_checkbox_set(control_id_recomm_change, expected_initiating_coverage)
                end
                found_match = true
                break
            end
        rescue => err
            raise  "ERROR: For stock #{i}: #{err}"
        end
    end
    if (found_match != true)
        raise "ERROR: Stock (#{expected_stock_name}) is not found on the page."
    end
end

# #---------------------------------------------

def assert_is_file_uploaded(element)
    control_name = get_attribute_name_of_element(element)
    control_id = get_control_id(control_name)
    case control_name
    when /PDF/
        actual_text = selenium_get_text(control_id)
        expected_file_name = $pdf_filename
        expected_file_size = element.attributes["expected_file_size"]
        expected_text = "#{expected_file_name} (#{expected_file_size})Remove"
        assert_is_text_equl(actual_text, expected_text)
    when /SC/
        actual_text = selenium_get_text(control_id)
        expected_file_name = element.attributes["expected_file_name"]
        expected_file_size = element.attributes["expected_file_size"]
        expected_contacts = element.attributes["expected_contacts"]
        expected_text = "#{expected_file_name} (#{expected_file_size})  Remove  (Not sent. Will be sent to #{expected_contacts} contacts)"
        assert_is_text_equl(actual_text, expected_text)
    when /HC/
        actual_text = selenium_get_text(control_id)
        expected_file_name = element.attributes["expected_file_name"]
        expected_file_size = element.attributes["expected_file_size"]
        expected_contacts = element.attributes["expected_contacts"]
        expected_text = "#{expected_file_name} (#{expected_file_size})  Remove  (Not sent. Will be sent to #{expected_contacts} contacts)"
        assert_is_text_equl(actual_text, expected_text)
    else
        raise "ERROR: File control '#{control_name}' is not recognized."
    end
end

# #---------------------------------------------

def handler_for_verify_STK(element_verify_STK)
    assert_is_stock_present(element_verify_STK)
end

# #---------------------------------------------

def handler_for_verify_INP(element_verify_INP)
    assert_is_file_uploaded(element_verify_INP)
end

# #---------------------------------------------

def handler_for_verify_SPN(element_verify_SPN)
    control_name = get_attribute_name_of_element(element_verify_SPN)
    control_id = get_control_id(control_name)
    value_unprocessed = get_attribute_value_of_element(element_verify_SPN)
    value = process_value_to_see_if_property_is_used(value_unprocessed)
    assert_contain(control_id, value)
end

# #---------------------------------------------

def drag_publication_drop_to_essential_category(ul_id, pub_text, category_id)
    li_count = get_listview_item_count(ul_id)
    bFound = false
    1.upto(li_count.to_i) do |i|
        text = selenium_get_text("//ul[@id='#{ul_id}']/li[#{i}]//td[2]")
        if (text.eql?(pub_text) )
            pub_id = get_listview_item_id(ul_id, i-1)
            puts pub_id
            selenium_drag_and_drop(pub_id, category_id)
            bFound = true
            break
        end
    end
    if !bFound
        raise "ERROR: Listview Item [#{pub_text}] is not found in Listview |#{ul_id}|"
    end
end

# #---------------------------------------------

def drag_and_drop_wapper(ul_id, pub_txt, category_id)
    #~ set_value_to_textbox("regionToFind", "Global")
    #~ set_value_to_dropdown("searchPubType", "Flyer")
    selenium_click("go")
    wait_for_child(ul_id)
    drag_publication_drop_to_essential_category(ul_id, pub_txt, category_id)
    wait_for_child(category_id)
    selenium_click("consolidate")
    wait_for_page_to_load
    selenium_click("editConsolidation")
    wait_for_page_to_load
end